<template>
    <div>
        <div>
            <a-button type="primary"  @click="handleZhifu" >
              批量支付
            </a-button>
        </div>
        <ma-crud :options="options" :columns="columns" ref="crudRef" @selection-change="setSelectedKeys" :selected-keys="ids?.value">
          <template #detail="{ record }">
            <a-popover :title="`收费明细（合计金额：${record.pay_price}）`" position="right">
              <a-link>明细</a-link>
              <template #content>
                <div style='min-width:300px'>
                  <a-table :columns="tablecolumnsts" :data="record.detail" :pagination='false' :span-method="spanMethodAll" :bordered="{wrapper: true, cell: true}" />
                </div>
              </template>
            </a-popover>
          </template>
          <template #pay_status="{ record }">
            <div>{{ record.pay_status == 1?'已支付':record.pay_status == 2 && record.is_wait_check == 0?'未支付':record.pay_status == 2 && record.is_wait_check == 1?'待审核':record.pay_status == 3?'已退款':'已取消' }}</div>
          </template>
        </ma-crud>
        <div class='lg:flex'>
          <div style='width:300px'>已支付金额小计：{{xiaoji}}</div>
        </div>
        <a-modal :mask-closable="false"  v-model:visible="zhifuShow" title="批量支付" @cancel="handlezhifuQuxiao" :width="800" ok-text='确定' :on-before-ok="handelzhifuOk">
          <div style="display: flex;align-items: center;margin-bottom: 2%;">
            <div style="width: 80px;">结算方式</div>
            <a-radio-group v-model="jiesuan" :options="jiesuanOptions" />
          </div>
          <div v-if='jiesuan == 3'>
            <div style="display: flex;align-items: center;margin-bottom: 2%;">
              <div style="width: 80px;">支付方式</div>
              <a-radio-group v-model="zhifu" :options="zhifuOptions" />
            </div>
            <div style="display: flex;align-items: center;margin-bottom: 2%;">
              <div style="width: 80px;">开户行</div>
              <div >{{opening_bank}}</div>
            </div>
            <div style="display: flex;align-items: center;margin-bottom: 2%;">
              <div style="width: 80px;">收款账户</div>
              <div >{{account}}</div>
            </div>
            <div style="display: flex;align-items: center;margin-bottom: 2%;">
              <div style="width: 80px;">开户名称</div>
              <div >{{account_name}}</div>
            </div>
            <div style="display: flex;margin-bottom: 2%;">
              <div style="width: 80px;">上传凭证</div>
              <ma-upload v-model="fileList" returnType='url' />
            </div>
          </div>
        </a-modal>
    </div>
  </template>
  
  <script setup>
  import {ref, shallowRef,reactive,computed,onMounted,defineProps } from "vue";
  import FinancialPayOrder from "@/api/financial/financialPayOrder";
  import { request } from "@/utils/request.js";
  import {cloneDeep, get, isEmpty} from "lodash";
  import {Message} from "@arco-design/web-vue";
  import tool from '@/utils/tool'
  import dept from "@/api/system/dept";
  const env = ref(import.meta.env);
  const token = ref(tool.local.get(import.meta.env.VITE_APP_TOKEN_PREFIX));
  const crudRef = ref()
  const visible = ref(false)
  const editPayItem = ref({})
  const editRef = ref({})
  const data = ref([])
  const refundRef = ref()
  const pay_price = ref('')
  const pay_price_item = ref('')
  const remark = ref('')
  const itemDetail = ref()
  const pay_method = ref([])
  const opening_bank = ref('')
  const account = ref('')
  const account_name = ref('')
  const zhifuShow = ref(false)
  const ids = ref([])
  const zhifu = ref('3')
  const jiesuan = ref('')
  const fileList = ref('')
  const xiaoji = ref(0)
  const zhifuOptions = ref([
      { label: '对公转账', value: '3' },
      { label: '现金', value: '2' },
      { label: '惠支付', value: '1' },
  ])
  const jiesuanOptions = ref([
      
  ])
  const props = defineProps({
    info: {
        default: "",
    },
  });
  const  spanMethodAll= ({record,rowIndex, columnIndex}) => {
      if (rowIndex === record.weizhi - record.weizhizong && columnIndex === 0) {
        return {rowspan: record.weizhizong,colspan:1}
      }
  
     
  };
  const handleZhifu = ()=>{
    if(ids.value.length == 0){
      return Message.error('请选择需要支付的订单')
    }
    jiesuan.value = ''
    zhifu.value = '3'
    fileList.value = ''
    zhifuShow.value = true
  }
  const handlezhifuQuxiao = ()=>{
    zhifuShow.value = false
  }
  const handelzhifuOk = async ()=>{ // 支付成功
    let obj = {}
    if(jiesuan.value == 1 || jiesuan.value == 2){
      obj.pay_type = jiesuan.value == 1?'money':'periodic'
      obj.ids = ids.value.join(',')
    }
    if(jiesuan.value == 3){
      obj.pay_type = 'now_pay'
      obj.ids = ids.value.join(',')
      obj.now_pay_type = zhifu.value
      obj.transfer_proof_images = fileList.value
      obj.payment_method = zhifu.value
      obj.settlement_method = 1
      obj.notes = ''
      // obj.pay_order_id = this.zhifu_id    // 交易单号
      obj.dept_id = loadData.dept_id    // 公司
      obj.opening_bank = opening_bank.value    // 开户行
      obj.account = account.value    // 收款账户
      obj.account_name = account_name.value    // 开户行名称
    }
    let res = await request({
          url: "financial/payOrder/pay",
          method: "post",
          data: obj,
        })
    if(res.code == 200){
          jiesuan.value = ''
          zhifu.value = '3'
          fileList.value = ''
          ids.value = []
          zhifuShow.value = false
          crudRef.value.refresh()
          Message.success(res.message);
          return true
    }else{
          Message.error(res.message);
          return false
    }
    
  }
  const handleSOrt = (ceshiArr)=>{
    let arr = []           // 最终数据
    let linshiArr = []     //  未匹配的放数组里
    let linshititle = ''   // 临时变量
    ceshiArr.map((v,i)=>{
      if(i == 0){
        linshititle = v.name
        arr.push(v)
      }else{
        if(linshititle == v.name){
          arr.push(v)
        }else{
          linshiArr.push(v)
        }
      }
    })
    ceshiArr.map((v,i)=>{
      if(linshiArr.length != 0){
        linshiArr.map((vv,ii)=>{
          if(ii == 0){
            linshititle = linshiArr[0].name
            arr.push(linshiArr.shift())
          }else{
            if(linshititle == vv.name){
              arr.push(linshiArr.slice(ii,1))
            }
          }
          
        })
        
      }
    })
    arr.sort((a, b) => a.car_nos.localeCompare(b.car_nos));
    return arr
  }
  
  const setSelectedKeys = (val) => {
    ids.value = val;
  };
  const getaccount = (type) =>{
    request({
          url: "system/dataDict/index",
          method: "get",
          params: {
            page:1,
                      pageSize:10,
                      type_id:type
          },
        }).then((res) => {
          opening_bank.value = res.data.items[0].value
                  account.value = res.data.items[1].value
                  account_name.value = res.data.items[2].value
        });
  }
  const options = reactive({
    id: 'flyos_financial_pay_order',
    rowSelection: {
      showCheckedAll: true
    },
    pk: 'id',
    operationColumn: true,
    operationWidth: 100,
    autoRequest:true,
    showSummary: false,
    summary: [
          {
              dataIndex: "pay_price",
              action: "sum",
          },
          
      ],
    formOption: {
      viewType: 'modal',
      width: 600
    },
    api: FinancialPayOrder.getdaozhanList,
    
    beforeRequest: (params) => {
          params.send_id= props.info.id;
          params.type= 2;

      },
    afterRequest: (params) => {
        if(params.length != 0){
      request({
        url: "system/userContract/remote",
        method: "post",
        data: {
          openPage: false,
					remoteOption:{
						filter: {id: ["=", params[0].send.contract_id]},
					}
        },
      }).then((res) => {
        let objarr = [
          { label: '预付款', value: '1',disabled:true },
          { label: '周期结算', value: '2',disabled:true },
          { label: '现结', value: '3',disabled:true },
        ]
        pay_method.value = res.data[0].pay_method.split(',')
        pay_method.value.map((v,i)=>{
          objarr.map((vv,ii)=>{
            if(v == vv.value){
              vv.disabled = false
            }
          })
        })
        jiesuanOptions.value = objarr
        res.data.map((v,i)=>{
						if(v.sign_dept_id == 7){
							getaccount(41)
						}
						if(v.sign_dept_id == 10){
							getaccount(42)
						}
					})
      });
    }
    let number = 0
		params.map((v, i) => {
			let arr = []
      let arrs = []
      v.pay_price = (v.pay_price - 0).toFixed(2)
      if(v.pay_status == 1){
        number += (v.pay_price - 0)
      }
      v.detail.map((vv,ii)=>{
        vv.car_nos = v.send.car_no
        vv.no_tax_price = (vv.no_tax_price - 0 ).toFixed(2)
          vv.tax_price = (vv.tax_price - 0 ).toFixed(2)
          vv.pay_real_price = (vv.pay_real_price - 0 ).toFixed(2)
          vv.pay_price = (vv.pay_price - 0 ).toFixed(2)
          vv.discount_price = (vv.discount_price - 0 ).toFixed(2)
        if(vv.pay_price != '0.00' && vv.is_confirm == 1){
          arr.push(vv)
        }
      })
      v.detail = handleSOrt(arr)
      let carArr = []
      v.detail.map((vv,ii)=>{
        carArr.push(vv.car_nos)
      })
      
      var newArr = carArr.filter(function(item,index){
        return carArr.indexOf(item) === index;  // 因为indexOf 只能查找到第一个  
      });
      let numArr = []
      newArr.map((vv,ii)=>{
        let num = 0
        let name = ''
        carArr.map((vvv,iii)=>{
          if(vv == vvv){
            num++
            name = vvv
          }
        })
        numArr.push({car_no:name,weizhi:num,weizhizong:num})
      })
      let weizhiArr = []
      let weizhinum = 0
      numArr.map((vv,ii)=>{
        weizhinum += vv.weizhi
        weizhiArr.push({car_no:vv.car_no,weizhi:weizhinum,weizhizong:vv.weizhizong})
      })
      v.detail.map((vv,ii)=>{
        weizhiArr.map((vvv,iii)=>{
          if(vv.car_nos == vvv.car_no){
            vv.weizhi = vvv.weizhi
            vv.weizhizong = vvv.weizhizong
          }
        })
      })
      if(v.pay_status != 2){
        v.disabled = true
      }
      if(v.pay_status == 2 && v.is_wait_check == 1){
        v.disabled = true
      }
      v.order_no = v.driver_order?.order_no || ''
		});
    xiaoji.value = number.toFixed(2) 
    }
  })
  const columns = reactive([
    {
      title: "",
      dataIndex: "id",
      formType: "input",
      addDisplay: false,
      editDisplay: false,
      hide: true,
      commonRules: {
        required: true,
        message: "请输入"
      }
    },
    
    {
      title: "账单单号",
      dataIndex: "order_number",
      width:160,
      formType: "input",
    },
    
    {
      title: "客户名称",
      dataIndex: "dept_id",
      search: false,
      width:140,
      common: true,
    },
    
    {
      title: "交易金额",
      width:100,
      dataIndex: "pay_price",
    },
    {
      title: "收费明细",
      dataIndex: "detail",
      width:100,
      formType: "input",
    },
    {
      title: "支付方式",
      dataIndex: "pay_type",
      formType: "select",
      width:100,
      dict: {
        data: [
          {
            label: "现结",
            value: "now_pay"
          },
          {
            label: "周期结算",
            value: "periodic"
          },
          {
            label: "预付款",
            value: "money"
          }
        ],
        translation: true
      }
    },
    {
      title: "支付类型",
      dataIndex: "now_pay_type",
      width:100,
      formType: "select",
      dict: {
        data: [
          {
            label: "惠支付",
            value: "1"
          },
          {
            label: "现金",
            value: "2"
          },
          {
            label: "对公转账",
            value: "3"
          }
        ],
        translation: true
      }
    },
    {
      title: "支付状态",
      dataIndex: "pay_status",
      formType: "select",
      width:100,
      dict: {
        data: [
          {
            label: "已支付",
            value: "1"
          },
          {
            label: "未支付",
            value: "2"
          },
          {
            label: "已退款",
            value: "3",
          },
          {
            label: "已取消",
            value: "4",
          }
        ],
        translation: true
      }
    },
    {
      title: "支付日期",
      dataIndex: "pay_date",
      width:180,
      formType: "date",
      showTime: true
    },
    {
      title: "创建时间",
      dataIndex: "created_at",
      formType: "date",
      width:180,
      addDisplay: false,
      editDisplay: false,
      showTime: true
    },
    {
      title: "备注",
      dataIndex: "remark",
      formType: "input",
      width:180,
      addDisplay: false,
      editDisplay: false,
    },
  ])
  const tablecolumns = [
        {
          title: '收费项目',
          dataIndex: 'pay_name',
  
        },
        {
          title: '金额',
          dataIndex: 'pay_price',
        },
        {
          title: '计费公式',
          dataIndex: 'chi_price_role',
        },
  ];
  const tablecolumnsts = [
        {
          title: '车号',
          dataIndex: 'car_nos',
        },
        {
          title: '收费项目',
          dataIndex: 'pay_name',
  
        },
        {
          title: '不含税金额',
          dataIndex: 'no_tax_price',
        },
        {
            title: '税额',
            dataIndex: 'tax_price',
        },
        {
          title: '原金额',
          dataIndex: 'pay_price',
        },
        {
          title: '实际金额',
          dataIndex: 'pay_real_price',
        },
        {
            title: '优惠金额',
            dataIndex: 'discount_price',
        },
        {
          title: '天-D',
          dataIndex: 'day',
        },
        {
          title: '吨-T',
          dataIndex: 'weight',
        },
        {
          title: '车-C',
          dataIndex: 'car_no_value',
        },
        {
          title: '箱-X',
          dataIndex: 'box',
        },
        {
          title: '计费规则',
          dataIndex: 'chi_price_role',
        },
        {
          title: '备注',
          dataIndex: 'remark',
        },
  ];
  </script>
  
  <style scoped>
  
  </style>
  